<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect,
  useMessage,
  NFlex,
  NAvatar, NSelect
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import { getToken } from '@/utils'
import { formatDate, renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'

defineOptions({ name: '弹屏管理' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE
import default_image from "@/assets/images/mz.jpg"

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '弹屏管理',
  initForm: {},
  doCreate: api.createMiniAlert,
  doUpdate: api.updateMiniAlert,
  doDelete: api.deleteMiniAlert,
  refresh: () => $table.value?.handlerefresh(),
})
const data = reactive({
  token: getToken(),
  uploadAction: base_path+'api/mini/alert/file',
  TypeData: [],
  tag_options: [],
  parentData: [],
  deptOption: [],
  gotypeData: [],
  fileList: [],
  upload: null,
  fileListLength: 0
});
const deptOption = ref([])

onMounted(() => {
  api.getGoType().then((res) => (data.gotypeData = res.data))
  $table.value?.handleSearch()
})


//上传封面图
const message = useMessage();
const customRequestMethod = (options) => {
  const { file } = options.file;
  const formData = new FormData();
  formData.append('file', file);
  fetch(data.uploadAction, {
    method: 'POST',
    headers: options.headers,
    body: formData,
  })
      .then((response) => response.json())
      .then((data) => {
        console.log(data, 'datatat');
        if (data.code == 200) {
          modalForm.value.cover = data.data.url
          message.success('封面图上传成功');
          options.onProgress(data);
        }else{
          message.error(data.msg);
        }
      })
}
const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },

  },
  {
    title: '标题',
    key: 'name',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  },
  {
    title: '排序',
    key: 'order',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },

  {
    title: '封面图',
    key: 'cover',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
    render(row) {
      return h(NFlex, {},
          [h(NAvatar, {
            src: row.cover,
            width: 30,
            fallbackSrc: default_image,
          })]
      )

    },
  },
  {
    title: '开始时间',
    key: 'start_time',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '结束时间',
    key: 'end_time',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '禁用',
    key: 'is_active',
    width: 50,
    align: 'center',
    render(row) {
      return h(NSwitch, {
        size: 'small',
        rubberBand: false,
        value: row.is_active,
        loading: !!row.publishing,
        checkedValue: false,
        uncheckedValue: true,
        onUpdateValue: () => handleUpdateDisable(row),
      })
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 40,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
            h(
                NButton,
                {
                  size: 'small',
                  type: 'primary',
                  style: 'margin-right: 8px;',
                  onClick: () => {
                    handleEdit(row)
                  },
                },
                {
                  default: () => '编辑',
                  icon: renderIcon('material-symbols:edit', { size: 16 }),
                }
            ),
            [[vPermission, 'post/api/content/contents/update']]
        ),
      ]
    },
  },
]

// 修改用户禁用状态
async function handleUpdateDisable(row) {
  if (!row.id) return
  row.publishing = true
  row.is_active = row.is_active === false
  row.publishing = false
  try {
    await api.updateMiniAlert(row)
    $message?.success(row.is_active ? '已取消禁' : '已禁用')
    $table.value?.handleSearch()
  } catch (err) {
    // 有异常恢复原来的状态
    row.state = row.is_active === false ? true : false
  } finally {
    row.publishing = false
  }
}

const handleFinish = ({
                        file,
                        event
                      }) => {

  let data = (event?.target).response
  data = JSON.parse(data)
  if(data.code===200){
    file.url = data.data.url
    message.success("上传成功");
  }else{
    message.error(data.data);
  }

  return file;
}

const validateAddUser = {
  name: [
    {
      required: true,
      message: '请输入标题',
      trigger: ['input', 'blur'],
    },
  ]
}

</script>

<template>
  <NLayout has-sider wh-full>
    <NLayoutContent>
      <CommonPage show-footer title="弹屏管理">
        <template #action>
          <NButton v-permission="'post/api/content/contents/create'" type="primary" @click="handleAdd">
            <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建弹屏
          </NButton>
        </template>
        <!-- 表格 -->
        <CrudTable ref="$table" v-model:query-items="queryItems" :columns="columns" :get-data="api.getMiniAlert" :scroll-x="1200">
          <template #queryBar>
            <QueryBarItem label="名称" :label-width="40">
              <NInput v-model:value="queryItems.name" clearable type="text" placeholder="请输入名称"
                      @keypress.enter="$table?.handleSearch()" />
            </QueryBarItem>
          </template>
        </CrudTable>

        <!-- 新增/编辑 弹窗 -->
        <CrudModal v-model:visible="modalVisible" :title="modalTitle" :loading="modalLoading" @save="handleSave"
                   style="width: 350px !important;"
        >
          <NForm ref="modalFormRef" label-placement="left" label-align="left" :label-width="80"
                 :model="modalForm" :rules="validateAddUser"  >

            <NFormItem label="名称" path="name" style="width: 100%;">
              <NInput v-model:value="modalForm.name" clearable placeholder="请输入标题" />
            </NFormItem>
            <NFormItem label="排序" path="order">
              <NInputNumber style="width: 200px;" v-model:value="modalForm.order" clearable
                            placeholder="输入排序" :default-value="0" />
            </NFormItem>
            <NFormItem label="封面图" path="avatar">
              <NImage v-if="modalForm.cover" width="60" style="border-radius: 5px;margin-right: 15px;" :src="modalForm.cover"></NImage>
              <NUpload :action="data.uploadAction" :headers="{ token: data.token }" :max="1" :show-file-list=false
                       :custom-request="customRequestMethod" list-type="image">
                <NButton >上传</NButton>
              </NUpload>
            </NFormItem>

            <NFormItem label="跳转类型" path="go_type">
              <NSelect style="width: 200px; " v-model:value="modalForm.go_type"
                       :options="data.gotypeData" placeholder="请选择跳转类型" />
            </NFormItem>
            <NFormItem label="资源值" path="go_url">
              <NInput style="width: 200px;" v-model:value="modalForm.go_url" clearable placeholder="请输入跳转资源值" />
            </NFormItem>
            <NFormItem label="开始时间" path="start_time">
              <n-date-picker
                  v-model:formatted-value="modalForm.start_time"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="datetime"
                  placeholder="选择开始时间"
                  clearable
              />
            </NFormItem>
            <NFormItem label="截止时间" path="end_time">
              <n-date-picker
                  v-model:formatted-value="modalForm.end_time"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="datetime"
                  placeholder="选择结束时间"
                  clearable
              />
            </NFormItem>




          </NForm>
        </CrudModal>

      </CommonPage>
    </NLayoutContent>
  </NLayout>
  <!-- 业务页面 -->
</template>
